package com.example.demo.util;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

public class TreeUtils {

    //返回值改为List
    public static List<TreeNode> buildTree(List<TreeNode> pidList){
        AtomicReference<String> zichanIds = new AtomicReference<>("");
        Map<String,List<TreeNode>> pidListMap =
                pidList.stream().collect(Collectors.groupingBy(TreeNode::getPid));
        pidList.stream().forEach(item->{
            if("固定资产".equals(item.getLabel())){
                zichanIds.set(item.getValue());
            }
            item.setChildren(pidListMap.get(item.getValue()));
        });
        //返回结果也改为返回顶层节点的list
        return pidListMap.get(zichanIds.get());
    }

    //返回值改为List
    public List<String> buildCodes(List<TreeNode> pidList, String code){
        AtomicReference<String> zichanIds = new AtomicReference<>("");
        Map<String,List<TreeNode>> pidListMap =
                pidList.stream().collect(Collectors.groupingBy(TreeNode::getPid));

        pidList.stream().forEach(item->{
            if(code.equals(item.getCode())){
                zichanIds.set(item.getValue());
            }
            item.setChildren(pidListMap.get(item.getValue()));
        });

        List<TreeNode> resultList = pidListMap.get(zichanIds.get());

        //如果没有找到子节点，则就把本身返回
        if(resultList == null){
            codes.add(code);
            return codes;
        }
        for(TreeNode treeNode : resultList){
            this.getTreeCode(treeNode);
        }
        codes.add(code);
        return codes;
    }

    //递归获取code
    private void getTreeCode(TreeNode node){
        this.codes.add(node.getCode());
        if(node.getChildren() != null){
            for(TreeNode children : node.getChildren()){
                this.getTreeCode(children);
            }
        }
    }

    private List<String> codes = new LinkedList<>();

}
